package {
	import experiments.ExperimentCollection;
	import experiments.Hypothesis;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.Dictionary;
	
	import view.Graphic;

	[SWF(backgroundColor="#FFFFFF", frameRate="60", width="640", height="480")]    
	public class RandomColorTest extends Sprite
	{
		private static const INTERVALS:int = 50;
		
		private static const RED:String 	= "red";
		private static const GREEN:String 	= "green";
		private static const BLUE:String 	= "blue";
		
		private var _collection:ExperimentCollection;
		
		private var _dicExperimentToView:Dictionary;
		
		private var _tfExperiments:TextField;
		
		public function RandomColorTest()
		{
			_collection = new ExperimentCollection();
			_collection.addExperiment(RED, getRed, 0x00, 0xff);
			_collection.addExperiment(GREEN, getGreen, 0x00, 0xff);
			_collection.addExperiment(BLUE, getBlue, 0x00, 0xff);
			
			_dicExperimentToView = new Dictionary();
			var nIndex:int = _collection.numHypothesis;
			while(--nIndex>=0)
			{
				var experiment:Hypothesis = _collection.getHypothesisAt(nIndex);
				var viewGraphic:Graphic = new Graphic(this, INTERVALS, experiment.minValue, experiment.maxValue);
				viewGraphic.x = 50;
				viewGraphic.y = 100 * (1) + 50;
				switch(experiment.name)
				{
					case RED:
						viewGraphic.color = 0xff0000;
					break;
					case GREEN:
						viewGraphic.color = 0x00ff00;
					break;
					case BLUE:
						viewGraphic.color = 0x0000ff;
					break;
				}
				
				_dicExperimentToView[experiment] = viewGraphic;
			}
			
			_tfExperiments = new TextField();
			addChild(_tfExperiments);
			
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function getRed():int
		{
			return (genColor() & 0xff0000) >>> 16;
		}
		
		private function getGreen():int
		{
			return (genColor() & 0x00ff00) >>> 8;
		}
		
		private function getBlue():int
		{
			return (genColor() & 0x0000ff);	
		}
		
		private function genColor():int
		{
			return Math.round(Math.random() * 0xffffff);
		}
		
		private function onEnterFrame(event:Event):void
		{
			_collection.nextExperiment();
			var nIndex:int = _collection.numHypothesis;
			while(--nIndex>=0)
			{
				var experiment:Hypothesis = _collection.getHypothesisAt(nIndex);
				var viewGraphic:Graphic = _dicExperimentToView[experiment]
				viewGraphic.addExperiment(experiment.getResult());
				viewGraphic.draw();
			}
			
			_tfExperiments.text = "experiment count : "+_collection.numExperiments.toString();
			_tfExperiments.autoSize = TextFieldAutoSize.RIGHT;
		}
	}
}
